package com.sport.video.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.sport.video.common.dto.common.RequestParams;
import com.sport.video.common.enums.RespEnum;
import com.sport.video.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            String requestMessage = StreamUtils.copyToString(inputStream, Charset.defaultCharset());
            log.info("接收到APP请求，请求报文为：{}",requestMessage);
            Map<String, Object> map = doDealMessage(requestMessage);
        } catch (Exception e) {
            e.printStackTrace();
            int code = RespEnum.ERROR.code;
            String msg = RespEnum.ERROR.msg;
            if (e instanceof BusinessException){
                code = ((BusinessException) e).getErrorCode();
                msg = ((BusinessException) e).getErrorMsg();
            }
            throw new ZuulException(e,code,msg);
        }finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            }catch (Exception e1){
                log.error("构造响应消息出现异常，异常信息：" + e1.getMessage(), e1);
                int code = RespEnum.ERROR.code;
                String msg = RespEnum.ERROR.msg;
                throw new ZuulException(e1,code,msg);
            }
        }

        return null;
    }

    private Map<String, Object> doDealMessage(String requestMessage) {
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isBlank(requestMessage)) {
            throw new BusinessException(RespEnum.ERROR_REQ_MSG_NOT_EMPTY.code
                    , RespEnum.ERROR_REQ_MSG_NOT_EMPTY.msg);
        }
        RequestParams requestParams = JSON.parseObject(requestMessage, RequestParams.class);
        if (requestParams == null) {
            throw new BusinessException(RespEnum.ERROR_REQUEST_MSG_ILLEGAL.code
                    , RespEnum.ERROR_REQUEST_MSG_ILLEGAL.msg);
        }
        // 获取appid、APPSecret并判断是否为空
        String appId = requestParams.getAppId();
        if (StringUtils.isBlank(appId)) {
            throw new BusinessException(RespEnum.ERROR_APP_ID_EMPTY.code,
                    RespEnum.ERROR_APP_ID_EMPTY.msg);
        }

        //String appSecret = application.getAppSecret();
        String version = requestParams.getVersion();
        String serviceId = requestParams.getServiceId();
        long timestamp = requestParams.getTimestamp();

        //时间戳为空返回错误
        if (StrUtil.isEmptyIfStr(timestamp)) {
            throw new BusinessException(RespEnum.ERROR_TIMESTAMP_EMPTY.code, RespEnum.ERROR_TIMESTAMP_EMPTY.msg);
        }
        // 未知的接口版本返回错误
        if (StringUtils.isBlank(version)) {
            throw new BusinessException(RespEnum.ERROR_VERSION_EMPTY.code, RespEnum.ERROR_VERSION_EMPTY.msg);
        }
        // 未知服务ID返回错误
        if (StringUtils.isBlank(serviceId)) {
            throw new BusinessException(RespEnum.ERROR_UNKOWN_SERVICEID.code, RespEnum.ERROR_UNKOWN_SERVICEID.msg);
        }

        try {
            String encryptData = requestParams.getEncryptData();
            //支持h5不加密
            if (StringUtils.isNotBlank(encryptData)) {
                log.info("请求密文:{}", encryptData);
               /* String decryptData = SecureU.(encryptData, requestParams.getEncryptType(), appSecret, appId);*/
               // requestParams.setParam(JSON.parseObject(decryptData, Object.class));
            }
        } catch (Exception e) {
            log.error("解密失败:", e);
           /* throw new BusinessException(RespConstant.ERROR_REPORT_ENC_FAIL, RespConstant.ERROR_REPORT_ENC_FAIL_MS);*/
        }

        try {
            String signOld = requestParams.getSign();
            //支持h5不签名
            if (StringUtils.isNotBlank(signOld)) {
               /* //String signNew = Signature.createSign(requestParams, appSecret);
                log.info("报文签名，报文签名值：{}，服务端构造的签名值：{}", signOld, signNew);
                boolean isVerify = signOld.equals(signNew);
                if (!isVerify) {
                    throw new BusinessException(RespConstant.EROOR_FAIL_VERIFY, RespConstant.EROOR_FAIL_VERIFY_MS);
                }*/
            }
        } catch (Exception e) {
            log.error("验证签名失败:", e);
            //throw new BusinessException(RespConstant.EROOR_FAIL_VERIFY, RespConstant.EROOR_FAIL_VERIFY_MS);
        }

        result.put("requestParams", requestParams);
        //result.put("appSecret", appSecret);
        return result;
    }
}
